package com.solt.prism.dao.imp;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;

import org.apache.log4j.Logger;

import com.solt.prism.core.entity.News;
import com.solt.prism.core.similar.DocSimilar;
import com.solt.prism.dao.JosContent;

public class JosContentSqlServerVersionImp implements JosContent {
	private static Logger logger = Logger.getLogger(JosContentImp.class);
	private DateFormat dateFormater ;
	public static final String INSERT_NEWS_SQL = "INSERT INTO Information(title,abstract,[content],odering,published,DateCreate,ImageUrl,CategoryId,SourceUrl,modifiedDate,createdby,AllowComment) "
			+ " VALUES(?,?,?,?,?,?,?,?,?,?,?,?)";
	
	public static final String INSERT_RELATE_NEWS = "INSERT INTO InforRelated ([from], [to], [percent]) VALUES (?,?,?)";

	private JosContentSqlServerVersionImp() throws SQLException {
		dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
	}

	public static JosContentSqlServerVersionImp getJosContent()
			throws SQLException {
		return new JosContentSqlServerVersionImp();
	}
	
	@Override
	public int insertNews(News news, List<DocSimilar> relateNews) {
		int key = insertNews(news);
		insertRelateNew(key, relateNews);
		return key;
	}
	
	private int insertRelateNew (int newId, List<DocSimilar> relateNews) {
		Connection con = null;
		PreparedStatement pre = null;
		
		try {
			con = SqlConnectionPool.getSqlServerConnection();
			pre = con.prepareStatement(INSERT_RELATE_NEWS);
			for (DocSimilar doc : relateNews){
				pre.setInt(1, newId);
				pre.setInt(2, (int)doc.getDocid());
				pre.setFloat(3, doc.getPercent());
				pre.executeUpdate();
			}
		} catch (SQLException e) {
			logger.error(e);
			System.exit(-1);
		} finally {
			if (pre != null) {
				try {
					pre.close();
				} catch (SQLException e) {
					logger.warn(e);
				}
			}
			
			if (con != null) {
				try {
					con.close();
				} catch (SQLException e) {
					logger.warn(e);
				}
			}
		}
		
		return newId;
	}
	
	@Override
	public int insertNews(News news, int[] relateNews) {
		int key = insertNews(news);
		return key;
	}

	@Override
	public int insertNews(News news) {
		int insertedKey = 0;
		Connection connection = null;
		PreparedStatement insertPre = null;
		try {
			connection = SqlConnectionPool.getSqlServerConnection();
			insertPre = connection.prepareStatement(INSERT_NEWS_SQL,Statement.RETURN_GENERATED_KEYS);

			insertPre.setString(1, news.getTitle());

			insertPre.setString(2, news.getDescription());

			insertPre.setString(3, news.getHtmlContent());

			insertPre.setInt(4, 0);

			insertPre.setInt(5, 1);

			if (news.getCreateTime() == null) {
				news.setCreateTime(new Date(System.currentTimeMillis()));
			}
			insertPre.setString(6, dateFormater.format(news.getCreateTime()));

			
			if (news.getImgUrl() == null) {
				news.setImgUrl("");
			}
			insertPre.setString(7, news.getImgUrl());
			
			if (news.getCatId() == null) {
				logger.warn("Can't insert new without catId " + news.toString());
				return -1;
			}
			insertPre.setInt(8, news.getCatId());
			
			insertPre.setString(9, news.getSourceUrl().toString());
			if (news.getModifiedDate() == null) {
				news.setModifiedDate(news.getCreateTime());
			}
			insertPre.setString(10, dateFormater.format(news.getModifiedDate()));
			
			insertPre.setInt(11, 1);
			
			insertPre.setInt(12, 1);
			
			insertPre.executeUpdate();
			
			
			ResultSet re = insertPre.getGeneratedKeys();
			re.next();
			insertedKey = re.getInt(1);
			System.out.println("inserted db!");
			insertPre.close();
		} catch (SQLException e) {
			logger.warn(news.toString(),e);
		} catch (Exception e) {
			logger.error("", e);
		} finally {
			try {
				if (insertPre != null)
					insertPre.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}

			try {
				if (connection != null)
					connection.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}

		}

		return insertedKey;

	}

}
